package net.jueb.protobufs3.client;

import net.jueb.protobufs3.pojo.MessageProto;
import net.jueb.protobufs3.pojo.MessageProto.Login;
import net.jueb.protobufs3.pojo.MessageProto.Message;
import net.jueb.protobufs3.pojo.MessageProto.MessageType;
import net.jueb.protobufs3.pojo.MessageProto.Regist;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ProtoClientHandler extends ChannelHandlerAdapter{
	
	
	public Message getMessage(MessageType type)
	{
		Message.Builder messageBuilder = Message.newBuilder();//设置消息主体
		messageBuilder.setMsgId(Thread.currentThread().hashCode());//设置消息ID
		Login login = Login.newBuilder().setUsername("admin").setPassword("123456").build();
		Regist regist = Regist.newBuilder().setUsername("admin").setPassword("123456").setMail("xxx@qq.com").build();
		switch (type.getNumber()) {
		case MessageType.Type_Regist_VALUE:
			//装入登录消息
			messageBuilder.setMsgType(MessageType.Type_Regist);
			messageBuilder.setExtension(MessageProto.regist, regist);
			break;
		case MessageType.Type_Login_VALUE:
			//装入注册消息
			messageBuilder.setMsgType(MessageType.Type_Login);
			messageBuilder.setExtension(MessageProto.login, login);
			break;
		default:
			break;
		}
		//构建消息主体
		return messageBuilder.build();
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//发出注册请求
		ctx.writeAndFlush(getMessage(MessageType.Type_Regist));
		//发出登录请求
		ctx.writeAndFlush(getMessage(MessageType.Type_Login));
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
		Message m=(Message)msg;
		if(m==null)
		{
			return;
		}
		switch (m.getMsgType().getNumber()) {
		case MessageType.Type_Result_VALUE:
			System.out.println("收到回复:"+m.getExtension(MessageProto.result));
			break;
		default:
			System.out.println("收到回复:"+m);
			break;
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
